#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：guestbook_svc.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/8/12 上午9:43 
@explain : 
"""
import math
import time

from cerberus import Validator

from app import utils, dao
from app.types import appproto


class GuestBookService:
    @classmethod
    def get_guestbook_list(cls, uid: int = 0, is_lock: int = 2, key_type: str = '', keyword: str = '',
                           page: int = 1,
                           page_size: int = 10) -> utils.HttpResponse:
        where = {}
        where['parent_id'] = None
        if uid != 0:
            where['uid'] = uid
        if is_lock != 2:
            where['is_lock'] = is_lock
        if key_type != '' and keyword != '':
            where[key_type] = '%' + keyword + '%'
        total, result = dao.GuestbookQueryDao.list(page=page, page_size=page_size, **where)
        if total == 0:
            return utils.ResponseSuccess(None)
        records_list = []
        for record in result:
            parent_records = {'id': record.id, 'uid': record.uid, 'content': record.content,
                              'suggest': record.suggest, 'parent_id': record.parent_id,
                              'types': record.types, 'entryname': record.entryname,
                              'constructionunitname': record.constructionunitname,
                              'zbdwname': record.zbdwname, 'phonenumber': record.phonenumber,
                              'title': record.title, 'lock': record.lock,
                              'addtime': utils.StringUtil.format_timestamp_to_str(record.addtime), 'reply_data': []}
            records_list.append(parent_records)

        # records_list = cls.build_nested_records(records_list)
        res = {'items': records_list, 'total': total, 'current_page': page, 'pagesize': page_size,
               'total_page': math.ceil(total / page_size)}
        return utils.ResponseSuccess(res)

    @classmethod
    def get_guestbook_reply(cls, parent_id=0, page: int = 1, page_size: int = 10) -> utils.HttpResponse:
        where = {}
        if parent_id != 0:
            where['parent_id'] = parent_id
        total, result = dao.GuestbookQueryDao.list_reply(page=page, page_size=page_size, **where)
        if total == 0:
            return utils.ResponseSuccess(None)
        records_list = []
        for record in result:
            parent_records = {'id': record.id, 'uid': record.uid, 'content': record.content,
                              'suggest': record.suggest, 'parent_id': record.parent_id,
                              'types': record.types, 'entryname': record.entryname,
                              'constructionunitname': record.constructionunitname,
                              'zbdwname': record.zbdwname, 'phonenumber': record.phonenumber,
                              'title': record.title, 'lock': record.lock,
                              'addtime': utils.StringUtil.format_timestamp_to_str(record.addtime), 'reply_data': []}
            records_list.append(parent_records)
        res = {'items': records_list, 'total': total, 'current_page': page, 'pagesize': page_size,
               'total_page': math.ceil(total / page_size)}
        return utils.ResponseSuccess(res)

    @classmethod
    def build_nested_records(cls, records):
        # 创建一个字典，用于存储父级记录及其子级列表
        parent_records = {record['id']: record for record in records if record['parent_id'] is None}
        # 遍历所有记录，将子级添加到对应的父级record的reply_data列表中
        for record in records:
            if record['parent_id'] in parent_records:
                parent_records[record['parent_id']]['reply_data'].append(record)
        # 返回处理后的顶级记录列表
        return list(parent_records.values())

    @classmethod
    def add(cls, data: appproto.GuestBookRequestData) -> utils.HttpResponse:
        rules = {
            'content': {
                'type': 'string',
                'required': True
            }
        }
        validator = Validator(rules, allow_unknown=True)
        input_data = data.model_dump()
        print("document===", input_data)
        if not validator.validate(input_data):
            errmsg = ''
            if 'content' in validator.errors:
                errmsg = '内容必填 '
            return utils.ResponseFail(errmsg, -3)
        input_data['addtime'] = int(time.time())
        result = dao.GuestbookOperateDao.save(input_data)
        if result:
            return utils.ResponseSuccess("回复成功")
        else:
            return utils.ResponseFail("回复失败", -3)

    @classmethod
    def update(cls, data: appproto.GuestBookRequestData) -> utils.HttpResponse:
        res = dao.GuestbookOperateDao.update(data.model_dump())
        return utils.ResponseSuccess('更新成功')

    @classmethod
    def guestbook_del(cls, ids: list[int]) -> utils.HttpResponse:
        for v in ids:
            dao.GuestbookOperateDao.delete(v)
        return utils.ResponseSuccess("删除成功")
